package com.example.androidfinalproject.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Looper;
import android.widget.ImageView;

import com.example.androidfinalproject.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.atomic.AtomicBoolean;

public class StorageUtil {
    private static AtomicBoolean flag = new AtomicBoolean();
    private static AtomicBoolean success = new AtomicBoolean();

    public static boolean readImageFile(File file, String fileName, ImageView imageView) {
        try {
            File read_file = new File(file, fileName);
            if (read_file.exists()) {
                FileInputStream inputStream = new FileInputStream(read_file);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                imageView.setImageBitmap(bitmap);
                return true;
            } else {
                imageView.setImageResource(R.drawable.android);
                return false;
            }
        } catch (Exception e) {
            imageView.setImageResource(R.drawable.android);
        }
        return false;
    }

    public static boolean downloadImage(final File file, final String fileName, final String path) {
        flag.set(false);
        success.set(false);
        new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                flag.set(false);
                                success.set(false);
                                File write_file = new File(file, fileName);
                                try {
                                    Looper.prepare();
                                    URL url = new URL(path);
                                    URLConnection connection = url.openConnection();
                                    InputStream inputStream = connection.getInputStream();
                                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                    FileOutputStream outputStream =
                                            new FileOutputStream(write_file);
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                    outputStream.close();
                                    inputStream.close();
                                    success.set(true);
                                } catch (Exception ignored) {
                                }
                                flag.set(true);
                            }
                        })
                .start();
        while (!flag.get()) {}
        return success.get();
    }
}
